//
//  CountdownLabel.swift
//  ltsp
//
//  Created by jyvyi_ios on 2022/6/29.
//

import UIKit

class CountdownLabel: UILabel {

    var timer : Timer?
    
    var intervalNum : TimeInterval = 1
    
    var totalCount : Int = 60
    
    var finishedBlock : EmptyCompleteBlock?
    
    func startCountdown(){
        
        self.stopCountdown()
        
        let timer = Timer.scheduledTimer(timeInterval: self.intervalNum, target: self, selector: #selector(countdownEvent), userInfo: nil, repeats: true)
        RunLoop.main.add(timer, forMode: .common)
        self.timer = timer
        self.totalCount = 60
    }
    func stopCountdown(){
        
        self.timer?.invalidate()
        self.timer = nil
    }
    @objc func countdownEvent(){
        
        guard self.totalCount >= 0 else {
            self.finishedBlock?()
            self.stopCountdown()
            return
        }
        self.text = self.totalCount.toString() + "s"
        self.totalCount -= 1
    }
}
